package com.xinchen.aiowaste.ui.activity

import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.Button
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.Spinner
import android.widget.TextView
import androidx.activity.viewModels
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.maple.common.widget.spinner.KeyValSpinnerAdapter
import com.maple.model.data.KeyValData
import com.maple.model.entity.aio.LabelListEntity
import com.maple.model.entity.aio.StorehouseListEntity
import com.maple.utils.ext.toGone
import com.maple.utils.ext.toVisible
import com.maple.utils.util.LogUtils
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.xinchen.aiowaste.R
import com.xinchen.aiowaste.base.BaseActivity
import com.xinchen.aiowaste.ui.adapter.LabelListAdapter
import com.xinchen.aiowaste.vm.LabelListViewModel
import java.util.WeakHashMap

class LabelListActivity : BaseActivity() {
    private var llEmpty: LinearLayout? = null
    private var refreshLayout: SmartRefreshLayout? = null
    private var rvList: RecyclerView? = null
    private var spPrint: Spinner? = null
    private var etQrCode: EditText? = null
    private var tvStartTime: TextView? = null
    private var tvEndTime: TextView? = null

    private var btnReset: Button? = null
    private var btnSearch: Button? = null
    private var btnPrint: Button? = null

    override fun getLayoutId(): Int = R.layout.activity_label_list

    private val viewModel by viewModels<LabelListViewModel>()

    private val listAdapter: LabelListAdapter by lazy {
        LabelListAdapter(this).apply {
            this.setData(arrayListOf())
            this.setListener(object : LabelListAdapter.OnClickListener {
                override fun onItemClick(pos: Int, item: LabelListEntity.DataList?) {
                    item?.let {
                        listAdapter.onSelectedItem(pos, it)
                    }
                }
            })
        }
    }


    private val printStatusList: List<KeyValData> = arrayListOf(
        KeyValData("不限",""),
        KeyValData("未打印","0"),
        KeyValData("已打印","1")
    )
    private var printStatusData: KeyValData = printStatusList.first()

    private val printStatusAdapter: KeyValSpinnerAdapter by lazy {
        KeyValSpinnerAdapter(this).apply {
            this.setData(printStatusList)
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        setTitle("标签打印")
        showClockTime()
        onBackClick()

        llEmpty = findViewById(R.id.ll_empty)
        llEmpty?.setOnClickListener {
            onSearch()
        }
        refreshLayout = findViewById(R.id.refresh_layout)
        refreshLayout?.let {
            it.setEnableRefresh(true)//是否启用下拉刷新功能
            it.setEnableLoadMore(true)//是否启用上拉加载功能
            it.setOnRefreshListener { ref ->
                onRefresh()
            }
            it.setOnLoadMoreListener { ref ->
                onLoadMore()
            }
        }
        rvList = findViewById(R.id.rv_list)
        rvList?.let {
            it.layoutManager = LinearLayoutManager(this)
            it.adapter = listAdapter
        }
        spPrint = findViewById(R.id.sp_print)
        spPrint?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(adapterView: AdapterView<*>?, view: View?, i: Int, l: Long) {
                val item: KeyValData = printStatusAdapter.getItem(i) as KeyValData
                printStatusData = item
                onSearch()
            }
            override fun onNothingSelected(adapterView: AdapterView<*>?) {}
        }
        spPrint?.adapter = printStatusAdapter
        etQrCode = findViewById(R.id.et_qr_code)
        tvStartTime = findViewById(R.id.tv_start_time)
        tvEndTime = findViewById(R.id.tv_end_time)
        btnReset = findViewById(R.id.btn_reset)
        btnReset?.setOnClickListener {
            etQrCode?.setText("")
            etQrCode?.setText("")
            tvStartTime?.text = ""
            tvEndTime?.text = ""
            spPrint?.setSelection(0)
        }
        btnSearch= findViewById(R.id.btn_search)
        btnSearch?.setOnClickListener {
            onSearch()
        }
        btnPrint = findViewById(R.id.btn_print)
        btnPrint?.setOnClickListener {
            val item: LabelListEntity.DataList? = listAdapter.getSelectedItem()
            if(item != null) {
                showToast(item.wasteName)
            } else {
                showToast("请选择标签！")
            }
        }
    }

    override fun initData(savedInstanceState: Bundle?) {

        viewModel.defUI.showDialog.observe(this, Observer {
            showLoading()
        })

        viewModel.defUI.dismissDialog.observe(this, Observer {
            dismissLoading()
        })

        viewModel.defUI.toastEvent.observe(this, Observer {
            showToast(it)
        })
        viewModel.defUI.emptyEvent.observe(this, Observer {
            rvList?.toGone()
            llEmpty?.toVisible()
        })
        viewModel.refreshEvent.observe(this) {
            finishRefresh()
        }
        viewModel.loadMoreEvent.observe(this) {
            finishLoadMore()
        }

        viewModel.labelList.observe(this, Observer {
            LogUtils.logGGQ("====list====:${it.size}")
            llEmpty?.toGone()
            rvList?.toVisible()
            listAdapter.setData(it)
            setNoMoreData(viewModel.getNoMoreData())
        })
        viewModel.refreshLabelList.observe(this, Observer {
            listAdapter.setData(it)
            setNoMoreData(viewModel.getNoMoreData())
        })
        viewModel.loadMoreLabelList.observe(this, Observer {
            listAdapter.upDataList(it)
            setNoMoreData(viewModel.getNoMoreData())
        })

        onSearch()
    }

    private fun onSearch() {
        val isPrint: String = printStatusData.v
        val qrCode: String = etQrCode?.text.toString().trim()
        val createdAt: String = tvStartTime?.text.toString()
        val createdAt1: String = tvEndTime?.text.toString()

        viewModel.getLabelList(isPrint,qrCode, createdAt, createdAt1)
    }
    private fun onRefresh() {
        val isPrint: String = printStatusData.v
        val qrCode: String = etQrCode?.text.toString().trim()
        val createdAt: String = tvStartTime?.text.toString()
        val createdAt1: String = tvEndTime?.text.toString()

        viewModel.refreshLabelList(isPrint,qrCode, createdAt, createdAt1)
    }

    private fun onLoadMore() {
        val isPrint: String = printStatusData.v
        val qrCode: String = etQrCode?.text.toString().trim()
        val createdAt: String = tvStartTime?.text.toString()
        val createdAt1: String = tvEndTime?.text.toString()

        viewModel.loadMoreLabelList(isPrint,qrCode, createdAt, createdAt1)
    }

    private fun finishRefresh() {
        refreshLayout?.let {
            if (it.isRefreshing) it.finishRefresh()
        }
    }

    private fun setNoMoreData(noMoreData: Boolean) {
        refreshLayout?.setNoMoreData(noMoreData)
    }

    //结束加载更多
    private fun finishLoadMore() {
        refreshLayout?.let {
            if (it.isLoading) it.finishLoadMore()
        }
    }

}